import React from 'react';
import { View, Text, ScrollView, StyleSheet, Dimensions, SafeAreaView, TouchableOpacity, Image, Alert } from 'react-native';
import { useDetailScreen } from './hooks';
import SvgIcon from '../../components/SvgIcon';
import { DetailScreenProps } from './types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Toast } from '@ant-design/react-native';
import { logoutApi } from './api';
import outlogin from '../../assets/outlogin.png';
import Header from '../../components/Header';
import { getRouteByAction } from '../../utils/navigation';
import { getComponentByRoute } from '../../utils/componentLoader';

const { width } = Dimensions.get('window');
const ITEM_SIZE = width / 4;

const DetailScreen: React.FC<DetailScreenProps> = ({
    onNavigateToLogin,
    onNavigateToScreen,
    currentRoute
}) => {
    const { menuData } = useDetailScreen();

    // 返回主菜单
    const handleBackToMain = () => {
        // 如果是设备详情页面，返回到设备信息页面
        if (currentRoute === 'Device/DeviceInfo/DeviceDetail') {
            onNavigateToScreen('Device/DeviceInfo');
        }
        // 如果是点检任务详情页面，返回到点检任务页面
        else if (currentRoute === 'Device/DeviceSpot/DeviceSpotDetail') {
            onNavigateToScreen('Device/DeviceSpot');
        }
        // 新增：如果是设备报修详情页面，返回到设备报修列表
        else if (currentRoute === 'Device/DeviceRepairReport/DeviceRepairReportDetail') {
            onNavigateToScreen('Device/DeviceRepairReport');
        }
        // 新增：如果是维修任务详情页面，返回到维修任务列表
        else if (currentRoute === 'Device/DeviceRepair/DeviceRepairDetail') {
            onNavigateToScreen('Device/DeviceRepair');
        }
        // 新增：如果是保养任务详情页面，返回到保养任务列表
        else if (currentRoute === 'Device/DeviceMaintain/DeviceMaintainDetail') {
            onNavigateToScreen('Device/DeviceMaintain');
        }
        // 新增：如果是过程检详情页面，返回到过程检列表
        else if (currentRoute === 'Quality/Ipqc/IpqcDetail') {
            onNavigateToScreen('Quality/Ipqc');
        }
        // 新增：如果是总数过程检详情页面，返回到总数过程检列表
        else if (currentRoute === 'Quality/TotalIpqc/TotalIpqcDetail') {
            onNavigateToScreen('Quality/TotalIpqc');
        }
        // 新增：如果是来料检详情页面，返回到来料检列表
        else if (currentRoute === 'Quality/Iqc/IqcDetail') {
            onNavigateToScreen('Quality/Iqc');
        }
        // 新增：如果是总数来料检详情页面，返回到总数来料检列表
        else if (currentRoute === 'Quality/TotalIqc/TotalIqcDetail') {
            onNavigateToScreen('Quality/TotalIqc');
        }
        // 新增：如果是出库检详情页面，返回到出库检列表
        else if (currentRoute === 'Quality/Oqc/OqcDetail') {
            onNavigateToScreen('Quality/Oqc');
        }
        // 新增：如果是总数出库检详情页面，返回到总数出库检列表
        else if (currentRoute === 'Quality/TotalOqc/TotalOqcDetail') {
            onNavigateToScreen('Quality/TotalOqc');
        }
        // 新增：如果是成品检详情页面，返回到成品检列表
        else if (currentRoute === 'Quality/Fqc/FqcDetail') {
            onNavigateToScreen('Quality/Fqc');
        }
        // 新增：如果是总数成品检详情页面，返回到总数成品检列表
        else if (currentRoute === 'Quality/TotalFqc/TotalFqcDetail') {
            onNavigateToScreen('Quality/TotalFqc');
        }
        else {
            onNavigateToScreen(''); // 清空路由，返回主菜单
        }
    };

    const handleLogout = () => {
        Alert.alert(
            '确认退出',
            '确定要退出登录吗？',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确定',
                    onPress: handleLogoPress,
                },
            ]
        );
    };

    // 执行退出登录
    const handleLogoPress = async () => {
        try {
            console.log('用户确认退出，准备调用退出登录接口');
            // 调用退出登录接口
            const res = await logoutApi();
            // 清除本地存储的token
            await AsyncStorage.removeItem('token');
            // 显示退出成功提示
            Toast.success(res.msg || '已安全退出登录', 1);
            // 延迟跳转，让用户看到成功提示
            setTimeout(() => {
                onNavigateToLogin();
            }, 500);
        } catch (e: any) {
            console.log('退出登录接口异常:', e);
            // 即使接口调用失败，也清除本地token并跳转
            await AsyncStorage.removeItem('token');
            Toast.fail(e.message || '网络错误，但已清除本地登录状态', 1);
            // 延迟跳转
            setTimeout(() => {
                onNavigateToLogin();
            }, 500);
        }
    };

    // 卡片点击处理函数
    const handleCardPress = (item: any) => {
        // console.log('点击了卡片:', item.menu_name, 'action:', item.action);

        if (item.action) {
            const route = getRouteByAction(item.action);
            // console.log('跳转到路由:', route);

            if (route !== 'Detail') {
                onNavigateToScreen(route);
            } else {
                Toast.info('该功能正在开发中', 1);
            }
        } else {
            Toast.info('该功能暂未配置', 1);
        }
    };

    // 打印菜单数据中的 menu_name 和 action 字段
    // React.useEffect(() => {
    //     if (menuData && menuData.length > 0) {
    //         console.log('=== 菜单数据 menu_name 和 action 字段 ===');
    //         menuData.forEach((group: any, groupIndex: number) => {
    //             console.log(`分组 ${groupIndex + 1}:`, {
    //                 group_menu_name: group.menu_name,
    //                 group_action: group.action
    //             });

    //             if (Array.isArray(group.children)) {
    //                 group.children.forEach((item: any, itemIndex: number) => {
    //                     console.log(`  子项 ${itemIndex + 1}:`, {
    //                         menu_name: item.menu_name,
    //                         action: item.action
    //                     });
    //                 });
    //             }
    //         });
    //         console.log('=== 菜单数据打印完成 ===');
    //     }
    // }, [menuData]);

    // 如果有当前路由，渲染对应的组件
    if (currentRoute) {
        const Component = getComponentByRoute(currentRoute);
        if (Component) {
            return (
                <React.Suspense fallback={
                    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                        <Text>加载中...</Text>
                    </View>
                }>
                    <Component
                        onNavigateToLogin={onNavigateToLogin}
                        onBackPress={handleBackToMain}
                        onNavigateToScreen={onNavigateToScreen}
                    />
                </React.Suspense>
            );
        }
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: '#f5f5f5' }}>
            {/* 顶部固定区域 */}
            {/* <View style={local.header}>
                <Text style={local.title}>WMS仓库管理系统</Text>
                <TouchableOpacity onPress={handleLogout} style={local.headerRightBtn}>
                    <Image source={outlogin} style={{ width: 30, height: 30, marginTop: 20 }} />
                </TouchableOpacity>
            </View> */}
            <Header
                title="Aiiiss-MOM 终端系统"
                showBackButton={false}
                showRightButton={true}
                rightButtonIcon={outlogin}
                onRightPress={handleLogout}
                onNavigateToLogin={onNavigateToLogin}
            />
            <ScrollView style={{ flex: 1, backgroundColor: '#f5f5f5', paddingTop: 10 }}>
                {(menuData || []).map((group: any) => (
                    <View key={group.id} style={{ marginBottom: 10 }}>
                        <Text style={local.groupTitle}>{group.menu_name}</Text>
                        <View style={local.grid}>
                            {Array.isArray(group.children) && group.children.map((item: any) => (
                                <View key={item.id} style={local.itemBox}>
                                    <TouchableOpacity
                                        style={local.card}
                                        onPress={() => handleCardPress(item)}
                                        activeOpacity={0.7}
                                    >
                                        <View style={local.iconBox}>
                                            <SvgIcon uri={item.logo} width={42} height={42} />
                                        </View>
                                        <Text style={local.label} numberOfLines={1}>{item.menu_name}</Text>
                                    </TouchableOpacity>
                                </View>
                            ))}
                        </View>
                    </View>
                ))}
            </ScrollView>
        </SafeAreaView>
    );
};

const local = StyleSheet.create({
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 80,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        backgroundColor: '#fff',
        position: 'relative',
        zIndex: 10,
    },
    title: {
        fontSize: 22,
        fontWeight: 'bold',
        marginTop: 15,
        color: '#333',
    },
    headerRightBtn: {
        position: 'absolute',
        right: 0,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
        padding: 8,
    },
    groupTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginLeft: 12,
        marginBottom: 10,
        color: '#222',
    },
    grid: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        paddingHorizontal: 0,
    },
    itemBox: {
        width: ITEM_SIZE,
        alignItems: 'center',
        marginBottom: 4,
        padding: 0,
    },
    card: {
        width: '95%', // 或 '95%'，让卡片之间有极小的缝隙
        backgroundColor: '#fff',
        borderRadius: 5,
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 0,
        margin: 0,
        elevation: 2,
        shadowColor: '#000',
        shadowOpacity: 0.06,
        shadowRadius: 6,
        shadowOffset: { width: 0, height: 2 },
    },
    iconBox: {
        width: 40,
        height: 40,
        borderRadius: 8,
        backgroundColor: '#f5f5f5',
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 6,
    },
    icon: {
        width: 28,
        height: 28,
    },
    label: {
        fontSize: 13,
        color: '#222',
        textAlign: 'center',
        fontFamily: 'System',
    },
});

export default DetailScreen; 